﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Linq;
using System.Text;
using Fly.Log;
using Newtonsoft.Json;
using RN.ERP.DAL;
using RN.ERP.DTO;
using RN.ERP.Entity;
using RN.ERP.Entity.QD;
using RN.ERP.Entity.ResultModels;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;

using System.Transactions;
using RN.ERP.BLL.QD.Utilities;

using Fly.FlyCommon;
using Fly.Common.Linq;
using System.Data.SqlClient;
using Fly.Common.Log;

namespace RN.ERP.BLL.QD
{
    public partial class EnterpriseBLL : BaseEnterpriseBLL
    {
        private EnterpriseDAL EnterDAL = new EnterpriseDAL();
        #region dbContext
        private QD_Context dbContext
        {
            get
            {
                return (QD_Context)base.baseContext;
            }
        }

        public EnterpriseBLL()
        {
            base.baseContext = new QD_Context();
        }
        #endregion

        #region 私有方法
        private LogAndFlowHelper baseBll = new LogAndFlowHelper();
        private PersonBLL perbll = new PersonBLL();

        /// <summary>
        /// 插入日志记录
        /// </summary>
        /// <param name="content"></param>
        /// <param name="objectid"></param>
        /// <param name="user"></param>
        private void InsertUserLog(string content, string objectid, string funid, string ftype)
        {
            baseBll.InsertUserLog(content, objectid, funid, ftype);
        }

        /// <summary>
        /// 记录流程状态
        /// </summary>
        /// <param name="objectid"></param>
        /// <returns></returns>
        private void InsertFlowCode(string objectid, int codeType)
        {
            Entity.QD.Tb_FlowCode model = new Entity.QD.Tb_FlowCode
            {
                AreaCode = "02",
                CodeType = codeType,
                FlowCode = FlowHelper.GetQdFlowCode(0, 0, false),
                IsDel = false,
                ObjectId = objectid,
                UpdateTime = DateTime.Now
            };
            baseBll.AddFlowcode(model);
        }
        #endregion

        #region 查询
        public override bool IsOrgnizationCodeExists(string orgnizationCode, string corpType, string areaCode)
        {
            int count = dbContext.Corp_CompanyInfos.Count(c => c.OrginazationCode == orgnizationCode && c.Type == corpType);
            if (count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public override string GetCorpInfo(string corpUserGuid, string areaCode)
        {
            Guid guid;
            Entity.QD.Tb_Corp_CompanyInfo ret = new Entity.QD.Tb_Corp_CompanyInfo();
            if (!Guid.TryParse(corpUserGuid, out guid))
                return JsonConvert.SerializeObject(ret);

            using (QD_Context db = new QD_Context())
            {
                ret = db.Corp_CompanyInfos.FirstOrDefault(m => m.CorpUserGuid == guid);
                return JsonConvert.SerializeObject(ret);
            }
        }

        /// <summary>
        /// 获取外地入青的企业信息和入青负责人信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override List<DTO.tb_Corp_CompanyInfo_wdrq> GetCorpInfoWdrq(string corpUserGuid, string areaCode)
        {
            Guid guid;
            if (!Guid.TryParse(corpUserGuid, out guid))
            {
                return null;
            }

            StringBuilder strsql = new StringBuilder();
            strsql.Append("SELECT c.*,e.Name as  FZRName ,e.tel as FZRtel, e.mobile as FZRMobile,e.typeflag as typeflag FROM dbo.tb_Corp_CompanyInfo_wdrq c join Tb_emp_employee e on c.CorpUserGuid=e.CorpUserGuid");

            // strsql.Append(" where c.corpuserguid='" + corpUserGuid + "' and e.TypeFlag in  (6,11) ");

            strsql.Append(" where c.corpuserguid='").Append(corpUserGuid).Append("'");
            var list = dbContext.Database.SqlQuery<Entity.ResultModels.tb_Corp_CompanyInfo_wdrq_employee>(strsql.ToString()).ToList();
            var dtolist = new List<DTO.tb_Corp_CompanyInfo_wdrq>();
            foreach (var item in list)
            {
                DTO.tb_Corp_CompanyInfo_wdrq wdrq_D = new DTO.tb_Corp_CompanyInfo_wdrq();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(item, wdrq_D);
                dtolist.Add(wdrq_D);
            }
            return dtolist;

        }

        public override string GetCorpQualities(string corpUserGuid, string areaCode)
        {
            Guid guid;
            List<Entity.QD.tb_Corp_Quality> ret = new List<Entity.QD.tb_Corp_Quality>();
            if (!Guid.TryParse(corpUserGuid, out guid))
            {
                return JsonConvert.SerializeObject(ret);
            }
            ret = dbContext.Corp_CompanyQualities.Where(m => m.CorpUserGuid == guid && (m.IsDel == false || m.IsDel == null)).OrderByDescending(m1 => m1.IsMain).ToList();
            int cnt = ret.Count;
            return JsonConvert.SerializeObject(ret);
        }

        public override IList<Entity.QD.tb_Corp_Quality> GetCorpQualitiesByConditon(string condition, string areaCode)
        {
            string sql = "SELECT * FROM  tb_Corp_Quality WHERE (isdel==false || isdel is null) ";
            if (!string.IsNullOrEmpty(condition))
            {
                sql += condition;
            }
            sql += " order by ismain desc";

            System.Data.SqlClient.SqlParameter[] parameters = { };
            IList<Entity.QD.tb_Corp_Quality> qualist = dbContext.Database.SqlQuery<Entity.QD.tb_Corp_Quality>(sql, parameters).ToList<Entity.QD.tb_Corp_Quality>(); ;

            return qualist;
        }

        public override string GetCorpQuality(string qualityId, string areaCode)
        {
            Guid qualityGuid = Guid.Empty;
            if (Guid.TryParse(qualityId, out qualityGuid))
            {
                Entity.QD.tb_Corp_Quality quality = dbContext.Corp_CompanyQualities.SingleOrDefault(q => q.QualityGuid == qualityGuid);
                return JsonConvert.SerializeObject(quality);
            }
            else
            {
                return string.Empty;
            }
        }

        public override string GetCorpInfos(string condition, string areaCode)
        {
            var list = new List<Entity.QD.Tb_Corp_CompanyInfo>();
            try
            {
                //if (!StringHelper.SqlFilter(condition))
                //{
                list = new EnterpriseDAL().GetCorpInfos(condition);
                //}
            }
            catch
            {
            }
            return JsonConvert.SerializeObject(list);
        }

        public override int GetCorpInfosCount(int pageIndex, int pageSize, string condition, string areaCode)
        {

            int num = 0;
            try
            {
                //if (!StringHelper.SqlFilter(condition))
                //{
                num = new EnterpriseDAL().GetCorpInfosCount(pageIndex, pageSize, condition);
                //}
            }
            catch (Exception ex)
            {
            }
            return num;
        }

        public override string GetCorpSecurity(string corpUserGuid, string areaCode)
        {
            Guid userGuid = Guid.Empty;
            Entity.QD.Kh_CorpTable security = null;
            if (Guid.TryParse(corpUserGuid, out userGuid))
            {
                try
                {
                    security = dbContext.SecurityInfo.FirstOrDefault(s => s.CorpUserGuid == userGuid);
                }
                catch
                {
                    security = null;
                }
            }
            return JsonConvert.SerializeObject(security);
        }

        public override string GetCorpKind(string corpkind, string areaCode)
        {
            string areacode = ConfigurationManager.AppSettings["Area"].ToString().Substring(0, 2);
            List<Entity.QD.tb_Corp_CorpKind> corpkindlist = new List<Entity.QD.tb_Corp_CorpKind>();
            switch (corpkind)
            {
                case "31"://预制构件企业
                case "30"://预拌混凝土企业 
                case "90"://检测机构 
                    corpkindlist = dbContext.CorpKind.Where(c => c.Kind == 90).ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
                case "55"://代建单位    
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1055").ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
                case "15"://施工总包 
                case "17"://外地入青企业
                case "7330"://市政施工总包
                    corpkindlist = dbContext.CorpKind.Where(c => (c.Kind == 1 || c.Kind == 2 || c.Kind == 3) && c.ClassKind == "1000").ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
                case "16"://专业承包
                    if (areacode != "09")
                    {
                        corpkindlist = dbContext.CorpKind.Where(c => c.Kind == 2 && c.ClassKind == "1000").ToList<Entity.QD.tb_Corp_CorpKind>();
                    }
                    else
                    {
                        corpkindlist = dbContext.CorpKind.Where(c => c.Kind == 2 && c.ClassKind == "3000").ToList<Entity.QD.tb_Corp_CorpKind>();
                    }
                    break;
                case "43"://劳务
                    corpkindlist = dbContext.CorpKind.Where(c => c.Kind == 3 && c.ClassKind == "1000").ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
                case "42"://监理
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1021").ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
                case "45"://建设单位            
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1045").ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
                case "46"://造价咨询单位
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1046").ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
                case "47"://勘察设计单位
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1047").ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
                case "105"://招标代理资质等级
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1105").ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
                case "":
                    corpkindlist = dbContext.CorpKind.Where(c => c.ID > 0).ToList<Entity.QD.tb_Corp_CorpKind>();
                    break;
            }
            return JsonConvert.SerializeObject(corpkindlist);
        }

        public override string GetQualityGrade(string dicquery, string areaCode)
        {
            if (!string.IsNullOrEmpty(dicquery))
            {
                DictionaryQuery query = JsonConvert.DeserializeObject<DictionaryQuery>(dicquery);
                if (query != null)
                {
                    var qualitygradelist = dbContext.Dictionarys.Where(d => d.ParentSID == query.parentsid && d.RootCode == query.rootcode).ToList();
                    return JsonConvert.SerializeObject(qualitygradelist);
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 本市/外埠市场 工程类获奖
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public override string GetCorpOuterPrize(string condition, int pageIndex, int pageSize, string areaCode)
        {
            ////bflag 扣分1,加分0
            string queryStr = string.Format("select * from e_OuterPrize  where 1=1 {0} order by e_OuterPrize.id desc", condition);
            var list = dbContext.Database.SqlQuery<Entity.QD.e_OuterPrize>(queryStr).OrderByDescending(m => m.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return JsonConvert.SerializeObject(list);
        }

        public override string GetCorpOuterPrizeCount(string condition, string areaCode)
        {

            string queryStr = string.Format("select * from e_OuterPrize  where 1=1 {0}", condition);
            string list = dbContext.Database.SqlQuery<Entity.QD.e_OuterPrize>(queryStr).ToList().Count.ToString();
            return list;
        }

        public override string GetOuterPrizeProjectInfoByID(string ID, string areaCode)
        {
            string CommandText = string.Format("SELECT * FROM e_OuterPrize where ID={0}", ID);
            var obj = dbContext.Database.SqlQuery<Entity.QD.e_OuterPrize>(CommandText).FirstOrDefault();
            return JsonConvert.SerializeObject(obj);
        }


        /// <summary>
        /// 企业工程类获奖
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public override string GetCorpProjectPrizePunish(string condition, int pageIndex, int pageSize, string areaCode)
        {
            string queryStr = string.Format("select * from e_ProjectPrizePunish where 1=1 and classid=2553 and bgrade in(105,99105) and AreaCode like '02%' {0} order by e_ProjectPrizePunish.id desc", condition);
            var list = dbContext.Database.SqlQuery<Entity.QD.e_ProjectPrizePunish>(queryStr).OrderByDescending(m => m.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return JsonConvert.SerializeObject(list);
        }
        public override string GetCorpProjectPrizePunishCount(string condition, string areaCode)
        {
            string queryStr = string.Format("select * from e_ProjectPrizePunish where 1=1 and classid=2553  and bgrade in(105,99105)  and AreaCode like '02%' {0} ", condition);
            string list = dbContext.Database.SqlQuery<Entity.QD.e_ProjectPrizePunish>(queryStr).ToList().Count.ToString();
            return list;
        }

        public override string GetProjectPrizePunishInfoByID(string ID, string areaCode)
        {
            string CommandText = string.Format("select * from e_ProjectPrizePunish where ID={0}", ID);
            var obj = dbContext.Database.SqlQuery<Entity.QD.e_ProjectPrizePunish>(CommandText).FirstOrDefault();
            return JsonConvert.SerializeObject(obj);
        }

        public override string GEtCheckTitleByKHID(string KHID, string areaCode)
        {
            string sql = string.Format("SELECT e_Score.Title AS LittleTitle, e_ScoreType.Title AS BigTitle FROM e_Score INNER JOIN e_ScoreType ON e_Score.TypeID = e_ScoreType.ID where  e_Score.ID={0}", KHID);
            var obj = dbContext.Database.SqlQuery<Entity.QD.e_Score>(sql).FirstOrDefault();
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 非工程类获奖
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public override string GetCorpPrizePunish(string condition, int pageIndex, int pageSize, string areaCode)
        {
            string queryStr = string.Format("SELECT e_PrizePunish.* from e_PrizePunish  left join e_flowtable  on e_PrizePunish.classid=e_flowtable.attchedclassid and e_PrizePunish.ID=e_flowtable.attchedid and e_flowtable.id=(select max(id) from e_flowtable where attchedclassid=e_PrizePunish.classid and attchedid=e_PrizePunish.id) WHERE 1=1 {0} ORDER BY e_flowtable.RegisterDate DESC ", condition);
            var list = dbContext.Database.SqlQuery<Entity.QD.e_PrizePunish>(queryStr).OrderByDescending(m => m.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return JsonConvert.SerializeObject(list);
        }

        public override string GetCorpPrizePunishCount(string condition, string areaCode)
        {
            string queryStr = string.Format("SELECT * from e_PrizePunish  left join e_flowtable  on e_PrizePunish.classid=e_flowtable.attchedclassid and e_PrizePunish.ID=e_flowtable.attchedid and e_flowtable.id=(select max(id) from e_flowtable where attchedclassid=e_PrizePunish.classid and attchedid=e_PrizePunish.id) WHERE 1=1 {0} ", condition);
            string list = dbContext.Database.SqlQuery<Entity.QD.e_PrizePunish>(queryStr).ToList().Count.ToString();
            return list;
        }

        public override string GetPrizePunishInfoByID(string ID, string areaCode)
        {
            string CommandText = string.Format("select * from e_PrizePunish where ID={0}", ID);
            var obj = dbContext.Database.SqlQuery<Entity.QD.e_PrizePunish>(CommandText).FirstOrDefault();
            return JsonConvert.SerializeObject(obj);
        }


        /// <summary>
        /// 查询e_FlowTable的历史记录
        /// </summary>
        /// <returns></returns>
        public override string GetAuditHistory(string condition, string areaCode)
        {
            string sql = string.Format("select * from e_FlowTable where 1=1 {0}  order by RegisterDate desc", condition);
            var list = dbContext.Database.SqlQuery<Entity.QD.e_FlowTable>(sql).ToList();
            return JsonConvert.SerializeObject(list);
        }

        /// <summary>
        /// 查询该企业下的所有工程业绩
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public override string GetCorpOuerPrizeAllProjectByCorpGuid(string condition, string areaCode)
        {
            string sql = string.Format("select e.*  from e_OuterPrize e  inner join tb_Corp_CompanyInfo c on e.CorpUserGuid = c.CorpUserGuid " +
                        " where 1=1 {0}  order by e.[bFlowStatus],[ProjectName] ", condition);
            var list = dbContext.Database.SqlQuery<Entity.QD.e_OuterPrize>(sql).ToList();
            return JsonConvert.SerializeObject(list);
        }

        public override string GetProjectPrizePunishByCorpGuid(string condition, string areaCode)
        {
            string sql = string.Format("  select e.*  from e_ProjectPrizePunish e  inner join tb_Corp_CompanyInfo c on e.CorpUserGuid = c.CorpUserGuid where 1=1 {0}  order by e.[bFlowStatus],e.[ProjectName] ", condition);
            var list = dbContext.Database.SqlQuery<Entity.QD.e_ProjectPrizePunish>(sql).ToList();
            return JsonConvert.SerializeObject(list);
        }

        public override string GetPrizePunishByCorpGuid(string condition, string areaCode)
        {
            string sql = string.Format("  select e.*  from e_PrizePunish e  inner join tb_Corp_CompanyInfo c on e.CorpUserGuid = c.CorpUserGuid " +
                    " where 1=1 {0} order by e.[bFlowStatus],e.[Title] ", condition);
            var list = dbContext.Database.SqlQuery<Entity.QD.e_PrizePunish>(sql).ToList();
            return JsonConvert.SerializeObject(list);
        }

        #endregion

        #region 企业端、主管端企业资质:注册添加、修改、查询、上报、审核 作者：
        /// <summary>
        /// 企业端:企业注册
        /// </summary>
        /// <param name="corpInfo"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpRegister(DTO.Tb_Corp_CompanyInfo corpInfo, DTO.T_Sys_Users userInfo, bool isReturnModel, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////1.添加T_Sys_Users
                    ////实例化Entity
                    Entity.T_Sys_Users userInfo_E = new Entity.T_Sys_Users();
                    ////用入参DTO为Entity赋值
                    EntityHelper.ConvertEntity2OtherEntity(userInfo, userInfo_E);
                    Guid gid = Guid.NewGuid();
                    userInfo_E.UserGuid = gid;
                    ////判断用户名是否重复
                    string regUserName = userInfo_E.UserName;
                    var hasUser = dbContext.T_Sys_Users.Where(t => t.UserName == regUserName).FirstOrDefault();
                    if (hasUser != null)
                    {
                        result.Message = String.Format("添加失败：用户{0}已存在！", regUserName);
                        result.Result = false;
                        result.ReturnValue = null;
                        return result;
                    }
                    ////添加
                    userInfo_E = dbContext.T_Sys_Users.Add(userInfo_E);
                    ////2.添加Tb_Corp_CompanyInfo
                    ////实例化Entity
                    Entity.QD.Tb_Corp_CompanyInfo corpInfo_E = new Entity.QD.Tb_Corp_CompanyInfo();
                    ////用入参DTO为Entity赋值
                    EntityHelper.ConvertEntity2OtherEntity(corpInfo, corpInfo_E);
                    corpInfo_E.CorpUserGuid = gid;
                    corpInfo_E.CorpGuid = Guid.NewGuid();
                    corpInfo_E.FlowCode = "0";
                    if (corpInfo_E.IsDel == null)
                    {
                        corpInfo_E.IsDel = false;
                    }
                    ////添加
                    corpInfo_E = dbContext.Corp_CompanyInfos.Add(corpInfo_E);
                    dbContext.SaveChanges();
                    ////3.流程 审核状态不存TB_FlowCode表,使用原表中flowcode字段 段仰广2013-5-13
                    ///InsertFlowCode(corpInfo_E.CorpUserGuid.ToString(), 8010);
                    ////4.日志
                    InsertUserLog("添加企业信息", corpInfo_E.ID.ToString(), "8010", "1");
                    tran.Commit();
                    result.Message = "添加成功。";
                    result.Result = true;
                    result.ReturnValue = gid;
                    if (isReturnModel)
                    {
                        ////用Entity为入参DTO赋值
                        EntityHelper.ConvertEntity2OtherEntity(corpInfo_E, corpInfo);
                        result.ReturnValue = corpInfo;
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "添加失败：" + ex.InnerException; ;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 企业端:企业注册信息上报（含企业内人员及资质）
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="isPostEmp"></param>
        /// <param name="isPostQuality"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpPost(string corpUserGuid, bool isPostEmp, bool isPostQuality, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "corpUserGuid不正确！";
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////企业注册信息上报
                    ////审核状态不存TB_FlowCode表,使用原表中flowcode字段
                    Entity.QD.Tb_Corp_CompanyInfo corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
                    if (corpinfo != null)
                    {
                        corpinfo.FlowCode = "0,019,";
                        dbContext.SaveChanges();
                    }
                    List<Entity.QD.tb_Corp_Quality> qualities = dbContext.Corp_CompanyQualities.Where(q => q.CorpUserGuid == cGuid).ToList();
                    if (qualities != null && qualities.Count > 0)
                    {
                        foreach (Entity.QD.tb_Corp_Quality quality in qualities)
                        {
                            quality.FlowCode = "0,019,";
                            dbContext.SaveChanges();
                        }
                    }
                    List<Entity.QD.tb_Emp_Employee> emplist = dbContext.Emp_Employee.Where(e => e.CorpUserGuid == cGuid).ToList();
                    if (emplist != null && emplist.Count > 0)
                    {
                        foreach (Entity.QD.tb_Emp_Employee employee in emplist)
                        {
                            employee.FlowCode = "0,019,";
                            dbContext.SaveChanges();
                        }
                    }
                    //Entity.QD.Tb_FlowCode flowcode = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == 8010 && f.IsDel == false).FirstOrDefault();
                    //if (flowcode != null)
                    //{
                    //    flowcode.FlowCode = "0,019";//FlowHelper.GetQdFlowCode(0, 1, false);
                    //    flowcode.UpdateTime = DateTime.Now;
                    //    dbContext.SaveChanges();
                    //}
                    //else
                    //{
                    //    flowcode = new Entity.QD.Tb_FlowCode();
                    //    flowcode.ObjectId = corpUserGuid;
                    //    flowcode.CodeType = 8010;
                    //    flowcode.IsDel = false;
                    //    flowcode.FlowCode = "0,019";//FlowHelper.GetQdFlowCode(0, 1, false);
                    //    flowcode.UpdateTime = DateTime.Now;
                    //    dbContext.FlowCodes.Add(flowcode);
                    //    dbContext.SaveChanges();
                    //}
                    #region 暂时不需要执行的代码
                    ////企业内人员
                    //if (isPostEmp)
                    //{
                    //    var cQual = dbContext.Emp_Manager.Where(f => f.CorpGuid.ToString() == corpUserGuid).ToList();
                    //    IList<string> empguids = new List<string>();
                    //    foreach (var item in cQual)
                    //    {
                    //        empguids.Add(item.EmpGuid.ToString());
                    //    }
                    //    perbll.EmpInfoPost(corpUserGuid, empguids);
                    //}
                    ////资质上报
                    //if (isPostQuality)
                    //{
                    //    IList<string> qualityGuid = new List<string>();
                    //    var cQual = dbContext.Corp_CompanyQualities.Where(f => f.CorpUserGuid.ToString() == corpUserGuid && f.IsDel == false).ToList();
                    //    foreach (var item in cQual)
                    //    {
                    //        qualityGuid.Add(item.QualityGuid.ToString());
                    //    }
                    //    CorpQualityPost(qualityGuid);
                    //} 
                    #endregion

                    ////日志
                    InsertUserLog("企业注册信息上报成功", corpUserGuid, "8010", "4");
                    tran.Commit();
                    result.Message = "企业注册信息上报成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "企业注册信息上报失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        public override string GetCorpostStatus(Guid corpuserguid, string areaCode)
        {
            Entity.QD.Tb_Corp_CompanyInfo corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == corpuserguid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
            if (corpinfo != null)
            {
                return corpinfo.FlowCode;
            }
            //string corpguid = corpuserguid.ToString();
            //Entity.QD.Tb_FlowCode flowcode = dbContext.FlowCodes.Where(f => f.ObjectId == corpguid && f.CodeType == 8010 && f.IsDel == false).FirstOrDefault();
            //if (flowcode != null)
            //{
            //    return flowcode.FlowCode;
            //}
            return string.Empty;
        }

        /// <summary>
        /// 企业端:企业基本信息变更
        /// </summary>
        /// <param name="corpInfo"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpInfoEdit(DTO.Tb_Corp_CompanyInfo corpInfo, DTO.Kh_CorpTable khCorpTable, DTO.tb_Corp_CompanyInfo_wdrq wdrq, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////1.修改Tb_Corp_CompanyInfo
                    ////查询数据库
                    Entity.QD.Tb_Corp_CompanyInfo dbCorpInfo = dbContext.Corp_CompanyInfos.Where(p => p.ID == corpInfo.ID && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                    ////修改赋值
                    if (dbCorpInfo != null)
                    {
                        if (dbCorpInfo.IsDel == null)
                        {
                            dbCorpInfo.IsDel = false;
                        }
                        Entity.QD.Tb_Corp_CompanyInfo corpInfo_E = new Entity.QD.Tb_Corp_CompanyInfo();
                        ////用入参DTO为Entity赋值
                        EntityHelper.ConvertEntity2OtherEntity(corpInfo, corpInfo_E);
                        ////修改赋值
                        EntityHelper.ConvertEntity2Entity<Entity.QD.Tb_Corp_CompanyInfo>(corpInfo_E, dbCorpInfo);
                        ////添加或修改安全生产许可证
                        Entity.QD.Kh_CorpTable khcorp = dbContext.SecurityInfo.Where(p => p.CorpUserGuid == dbCorpInfo.CorpUserGuid).FirstOrDefault();
                        Entity.QD.Kh_CorpTable khCorpTable_E = new Entity.QD.Kh_CorpTable();

                        ////用入参DTO为Entity赋值Kh_CorpTable
                        EntityHelper.ConvertEntity2OtherEntity(khCorpTable, khCorpTable_E);
                        if (khcorp != null)
                        {
                            ////修改赋值
                            EntityHelper.ConvertEntity2Entity<Entity.QD.Kh_CorpTable>(khCorpTable_E, khcorp);
                        }
                        else
                        {
                            dbContext.SecurityInfo.Add(khCorpTable_E);
                        }
                        if (wdrq != null)
                        {
                            ////添加外地入青信息
                            var wdcorp = dbContext.Corp_CompanyInfosWdrq.Where(p => p.CorpUserGuid == dbCorpInfo.CorpUserGuid).FirstOrDefault();
                            Entity.QD.tb_Corp_CompanyInfo_wdrq wdcorp_E = new Entity.QD.tb_Corp_CompanyInfo_wdrq();
                            ////用入参DTO为Entity赋值tb_Corp_CompanyInfo_wdrq
                            EntityHelper.ConvertEntity2OtherEntity(wdrq, wdcorp_E);
                            if (wdcorp != null)
                            {
                                ////修改赋值
                                EntityHelper.ConvertEntity2Entity<Entity.QD.tb_Corp_CompanyInfo_wdrq>(wdcorp_E, wdcorp);
                            }
                            else
                            {
                                dbContext.Corp_CompanyInfosWdrq.Add(wdcorp_E);
                            }
                        }

                        dbContext.SaveChanges();
                    }
                    ////2.日志
                    InsertUserLog("修改企业信息", corpInfo.ID.ToString(), "8010", "2");
                    tran.Commit();
                    result.Message = "修改成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "修改失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }

            return result;
        }

        /// <summary>
        /// 企业端:企业添加资质
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="qualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpQualityAdd(string corpUserGuid, IList<DTO.tb_Corp_Quality> qualities, bool isReturnModel, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            IList<Entity.QD.tb_Corp_Quality> returnQuality = new List<Entity.QD.tb_Corp_Quality>();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////1.添加tb_Corp_Quality
                    foreach (var item in qualities)
                    {
                        if (item != null)
                        {
                            item.IsDel = false;
                            // item.QualityGuid = Guid.NewGuid();
                            item.CorpUserGuid = Guid.Parse(corpUserGuid);
                            Entity.QD.tb_Corp_Quality corpQua_E = new Entity.QD.tb_Corp_Quality();
                            ////用入参DTO为Entity赋值
                            EntityHelper.ConvertEntity2OtherEntity(item, corpQua_E);

                            corpQua_E = dbContext.Corp_CompanyQualities.Add(corpQua_E);
                            dbContext.SaveChanges();
                            ////循环添加返回值
                            returnQuality.Add(corpQua_E);
                            ////3.流程
                            //InsertFlowCode(dbCorpQua.QualityGuid.ToString(), 8030);
                            ////4.日志
                            InsertUserLog("添加企业资质信息", corpQua_E.ID.ToString(), "8030", "1");
                        }
                    }
                    tran.Commit();
                    result.Message = "添加成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                    if (isReturnModel)
                    {
                        foreach (var item in returnQuality)
                        {
                            if (item.IsDel == null)
                            {
                                item.IsDel = false;
                            }
                            DTO.tb_Corp_Quality dtoCorpQuality = new DTO.tb_Corp_Quality();
                            ////用Entity为入参DTO赋值
                            EntityHelper.ConvertEntity2OtherEntity(item, dtoCorpQuality);
                            qualities.Add(dtoCorpQuality);
                        }
                        result.ReturnValue = qualities;
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "添加失败：：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }

            return result;
        }

        /// <summary>
        /// 修改企业资质
        /// </summary>
        /// <param name="quality"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpQualityEdit(DTO.tb_Corp_Quality quality, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    if (quality.IsDel == null)
                    {
                        quality.IsDel = false;
                    }
                    ////1.修改tb_Corp_Quality
                    ////查询数据库
                    Entity.QD.tb_Corp_Quality dbCorpQuality = dbContext.Corp_CompanyQualities.Where(p => p.QualityGuid == quality.QualityGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                    ////修改赋值
                    if (dbCorpQuality != null)
                    {
                        Entity.QD.tb_Corp_Quality tbCorpQuality_E = new Entity.QD.tb_Corp_Quality();
                        ////用入参DTO为Entity赋值
                        EntityHelper.ConvertEntity2OtherEntity(quality, tbCorpQuality_E);
                        EntityHelper.ConvertEntity2Entity<Entity.QD.tb_Corp_Quality>(tbCorpQuality_E, dbCorpQuality);
                    }
                    dbContext.SaveChanges();
                    ////2.日志
                    InsertUserLog("修改企业资质信息", dbCorpQuality.ID.ToString(), "8030", "2");
                    tran.Commit();
                    result.Message = "修改成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "修改失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }

            return result;
        }

        /// <summary>
        /// 删除企业资质
        /// </summary>
        /// <param name="qualityGuid"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpQualityDel(string qualityGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////1.修改tb_Corp_Quality
                    ////查询数据库
                    Guid quaGuid = Guid.Parse(qualityGuid);
                    Entity.QD.tb_Corp_Quality dbCorpQuality = dbContext.Corp_CompanyQualities.Where(p => p.QualityGuid == quaGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                    ////修改赋值
                    if (dbCorpQuality != null)
                    {
                        dbCorpQuality.IsDel = true;
                    }
                    dbContext.SaveChanges();
                    ////2.日志
                    InsertUserLog("删除企业资质信息", dbCorpQuality.ID.ToString(), "8030", "3");
                    tran.Commit();
                    result.Message = "删除成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "删除失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }

            return result;
        }

        /// <summary>
        /// 企业端:企业资质上报
        /// </summary>
        /// <param name="qualityGuid"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpQualityPost(IList<string> qualityGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var item in qualityGuid)
                    {
                        Guid quaGuid = Guid.Parse(item);
                        Entity.QD.tb_Corp_Quality dbCorpQuality = dbContext.Corp_CompanyQualities.Where(p => p.QualityGuid == quaGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                        if (dbCorpQuality != null)
                        {
                            if (dbCorpQuality.FlowCode.StartsWith("0,019,021"))
                            {
                                dbCorpQuality.FlowCode = "0,019,022,";
                            }
                            else
                            {
                                dbCorpQuality.FlowCode = "0,019,";
                            }
                            ////日志
                            InsertUserLog("企业资质上报成功", item, "8030", "4");
                            dbContext.SaveChanges();
                        }

                        //Entity.QD.Tb_FlowCode flowcode = dbContext.FlowCodes.Where(f => f.ObjectId == item && f.CodeType == 8030 && f.IsDel == false).FirstOrDefault();
                        //if (flowcode != null)
                        //{
                        //    flowcode.FlowCode = "0,019";//FlowHelper.GetQdFlowCode(0, 1, false);
                        //    flowcode.UpdateTime = DateTime.Now;
                        //    ////日志
                        //    InsertUserLog("企业资质上报成功", item, "8030", "4");
                        //    dbContext.SaveChanges();
                        //}
                    }
                    tran.Commit();
                    result.Message = "企业资质上报成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "企业资质上报失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 主管端:主管审核企业上报的注册信息(多个)
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="log"></param>
        /// <param name="flowCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpListAudit(IList<string> corpUserGuids, User_Log log, string flowCode, bool isunlockandback, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string returnString = string.Empty;
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var item in corpUserGuids)
                    {
                        Guid cGuid = Guid.Empty;
                        Guid.TryParse(item, out cGuid);
                        Entity.QD.Tb_Corp_CompanyInfo corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
                        if (corpinfo != null)
                        {
                            if (!isunlockandback && (corpinfo.FlowCode.StartsWith("1") || corpinfo.FlowCode.StartsWith("0,019,021")))
                            {
                                result.Result = false;
                                result.Message = "该企业已被主管审核，无需再次审核，请刷新页面";
                                return result;
                            }
                            corpinfo.FlowCode = flowCode;
                            corpinfo.Description = log.Notice;
                            ////日志
                            string message = string.Empty;
                            message = "操作成功";
                            baseBll.InsertDetailUserLog(message, item, "8010", "4", log);
                            dbContext.SaveChanges();

                            List<Entity.QD.tb_Corp_Quality> qualities = dbContext.Corp_CompanyQualities.Where(q => q.CorpUserGuid == cGuid).ToList();
                            if (qualities != null && qualities.Count > 0)
                            {
                                foreach (Entity.QD.tb_Corp_Quality quality in qualities)
                                {
                                    quality.FlowCode = flowCode;
                                    dbContext.SaveChanges();
                                }
                            }
                            List<Entity.QD.tb_Emp_Employee> emplist = dbContext.Emp_Employee.Where(e => e.CorpUserGuid == cGuid).ToList();
                            if (emplist != null && emplist.Count > 0)
                            {
                                foreach (Entity.QD.tb_Emp_Employee employee in emplist)
                                {
                                    employee.FlowCode = flowCode;
                                    dbContext.SaveChanges();
                                }
                            }
                        }
                    }
                    tran.Commit();
                    result.Message = "操作成功";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "操作失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 主管端:主管审核企业上报的注册信息(单个)
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="log"></param>
        /// <param name="flowCode"></param>
        /// <param name="isFinal"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpAudit(string corpUserGuid, string areaCode, User_Log log, string flowCode, string description, bool isFinal)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    Guid cGuid = Guid.Empty;
                    Guid.TryParse(corpUserGuid, out cGuid);
                    Entity.QD.Tb_Corp_CompanyInfo corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
                    if (corpinfo != null)
                    {
                        ////如果是退回状态则不处理
                        //if (corpinfo.FlowCode != "0,019,021" && corpinfo.FlowCode != "0,019,021,")
                        //{
                        corpinfo.FlowCode = flowCode;
                        corpinfo.Description = description;
                        if (corpinfo.tb_Corp_IsOuter == 1)//外地入青企业
                        {
                            Entity.QD.tb_Corp_CompanyInfo_wdrq corpinfowdrq = dbContext.Corp_CompanyInfosWdrq.Where(f => f.CorpUserGuid == cGuid).FirstOrDefault();
                            if (corpinfowdrq != null)
                            {
                                corpinfowdrq.FlowCode = flowCode;
                                dbContext.SaveChanges();
                            }
                        }
                        ////日志
                        baseBll.InsertDetailUserLog("审核企业信息成功", corpUserGuid, "8010", "4", log);
                        dbContext.SaveChanges();

                        List<Entity.QD.tb_Corp_Quality> qualities = dbContext.Corp_CompanyQualities.Where(q => q.CorpUserGuid == cGuid).ToList();
                        if (qualities != null && qualities.Count > 0)
                        {
                            foreach (Entity.QD.tb_Corp_Quality quality in qualities)
                            {
                                quality.FlowCode = flowCode;
                                quality.Description = description;
                                dbContext.SaveChanges();
                            }
                        }
                        List<Entity.QD.tb_Emp_Employee> emplist = dbContext.Emp_Employee.Where(e => e.CorpUserGuid == cGuid).ToList();
                        if (emplist != null && emplist.Count > 0)
                        {
                            foreach (Entity.QD.tb_Emp_Employee employee in emplist)
                            {
                                employee.FlowCode = flowCode;
                                employee.Description = description;
                                dbContext.SaveChanges();
                            }
                        }
                        //}
                        //else
                        //{
                        //    result.Message = "已退回不能审核！";
                        //    result.Result = false;
                        //    result.ReturnValue = null;
                        //    return result;
                        //}
                    }

                    //Entity.QD.Tb_FlowCode flowcodemodel = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.IsDel == false && f.CodeType == 8010).FirstOrDefault();
                    //if (flowcodemodel != null)
                    //{
                    //    flowcodemodel.FlowCode = flowCode;
                    //    flowcodemodel.AreaCode = areaCode;
                    //    flowcodemodel.RoleId = log.IsrtUserRole;
                    //    flowcodemodel.UpdateTime = DateTime.Now;
                    //    dbContext.SaveChanges();
                    //}
                    ////日志
                    baseBll.InsertDetailUserLog("操作成功", corpUserGuid, "8010", "4", log);
                    tran.Commit();
                    result.Message = "操作成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "操作失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 主管端:主管审核企业的资质
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="log"></param>
        /// <param name="flowCode"></param>
        /// <param name="isFinal"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpQualityAudit(string corpUserGuid, string areaCode, User_Log log, string flowCode, bool isFinal)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    Guid quaGuid = Guid.Parse(corpUserGuid);
                    Entity.QD.tb_Corp_Quality dbCorpQuality = dbContext.Corp_CompanyQualities.Where(p => p.QualityGuid == quaGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                    if (dbCorpQuality != null)
                    {
                        dbCorpQuality.FlowCode = flowCode;
                        dbContext.SaveChanges();
                    }

                    //Entity.QD.Tb_FlowCode flowcodemodel = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.IsDel == false && f.CodeType == 8030).FirstOrDefault();
                    //if (flowcodemodel != null)
                    //{
                    //    flowcodemodel.FlowCode = flowCode;
                    //    flowcodemodel.AreaCode = areaCode;
                    //    flowcodemodel.RoleId = log.IsrtUserRole;
                    //    flowcodemodel.UpdateTime = DateTime.Now;
                    //    dbContext.SaveChanges();
                    //}
                    ////日志
                    InsertUserLog("操作成功", corpUserGuid, "8030", "4");
                    tran.Commit();
                    result.Message = "操作成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "操作失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 主管端:主管审核企业的资质
        /// </summary>
        /// <param name="qualities"></param>
        /// <param name="areaCode"></param>
        /// <param name="log"></param>
        /// <param name="flowCode"></param>
        /// <param name="isFinal"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpQualityAuditByQualities(IList<string> qualities, string areaCode, User_Log log, string flowCode, bool isFinal)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var item in qualities)
                    {
                        Guid quaGuid = Guid.Parse(item);
                        Entity.QD.tb_Corp_Quality dbCorpQuality = dbContext.Corp_CompanyQualities.Where(p => p.QualityGuid == quaGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                        if (dbCorpQuality != null)
                        {
                            dbCorpQuality.FlowCode = flowCode;
                            ////日志
                            baseBll.InsertDetailUserLog("操作成功", item, "8030", "4", log);
                            dbContext.SaveChanges();
                        }
                        //Entity.QD.Tb_FlowCode flowcodemodel = dbContext.FlowCodes.Where(f => f.ObjectId == item && f.IsDel == false && f.CodeType == 8030).FirstOrDefault();
                        //if (flowcodemodel != null)
                        //{
                        //    flowcodemodel.FlowCode = flowCode;
                        //    flowcodemodel.AreaCode = areaCode;
                        //    flowcodemodel.RoleId = log.IsrtUserRole;
                        //    flowcodemodel.UpdateTime = DateTime.Now;
                        //    ////日志
                        //    baseBll.InsertDetailUserLog("审核企业资质成功", item, "8030", "4", log);
                        //    dbContext.SaveChanges();
                        //}
                    }
                    tran.Commit();
                    result.Message = "操作成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "操作失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 公共:查询企业信息列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public override IList<DTO.Tb_Corp_CompanyInfo> GetCompaniesInfo(string conditions, string areaCode)
        {
            ////调用DAL中的方法
            var list = new EnterpriseDAL().GetCorpInfos(conditions);
            var dtolist = new List<DTO.Tb_Corp_CompanyInfo>();
            foreach (var item in list)
            {
                DTO.Tb_Corp_CompanyInfo corpInfo_D = new DTO.Tb_Corp_CompanyInfo();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(item, corpInfo_D);
                dtolist.Add(corpInfo_D);
            }
            return dtolist;
        }

        /// <summary>
        /// 公共:查询企业详细信息
        /// </summary>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public override DTO.Tb_Corp_CompanyInfo GetCompanyInfo(string conditions, string areaCode)
        {
            ////调用DAL中的方法
            var detail = new EnterpriseDAL().GetCompanyInfo(conditions);
            var corpInfo_D = new DTO.Tb_Corp_CompanyInfo();
            ////用Entity为入参DTO赋值
            EntityHelper.ConvertEntity2OtherEntity(detail, corpInfo_D);
            return corpInfo_D;
        }

        /// <summary>
        /// 公共:查询企业资质
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Corp_Quality> GetCompanyQualities(string corpUserGuid, string conditions, string areaCode)
        {
            ////调用DAL中的方法
            var list = new EnterpriseDAL().GetCompanyQualities(corpUserGuid, conditions);
            var dtolist = new List<DTO.tb_Corp_Quality>();
            foreach (var item in list)
            {
                DTO.tb_Corp_Quality corpQuality_D = new DTO.tb_Corp_Quality();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(item, corpQuality_D);
                dtolist.Add(corpQuality_D);
            }
            return dtolist;
        }

        /// <summary>
        /// 公共:查询操作日志记录
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="code"></param>
        /// <param name="functionId"></param>
        /// <param name="isrtUser"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public override IList<User_Log> GetUserLog(string objectId, string codeType, string areaCode)
        {
            ////调用DAL中的方法
            var list = new EnterpriseDAL().GetUserLog(objectId, codeType);
            return list;
        }

        /// <summary>
        /// 公共:根据企业组织机构代码查询企业占用情况
        /// CorpRegisterValidationModel类包含bool的是否已注册，如果已经注册则包含Tb_Corp_CompanyInfo信息，和string的说明信息。
        /// </summary>
        /// <param name="corpCode"></param>
        /// <returns></returns>
        public override DTO.CorpRegisterValidationModel CorpRegisterValidate(string corpCode, string areaCode)
        {
            ////调用DAL中的方法
            var detail = new EnterpriseDAL().CorpRegisterValidate(corpCode);
            var detail_D = new DTO.CorpRegisterValidationModel();
            if (detail != null)
            {
                ////用Entity为入参DTO赋值
                detail_D.IsRegisted = detail.IsRegisted;
                detail_D.Message = detail.Message;
                EntityHelper.ConvertEntity2OtherEntity(detail.CorpInfo, detail_D.CorpInfo);
            }
            return detail_D;
        }

        /// <summary>
        /// 公共:查询企业审核信息列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public override List<Tb_Corp_CompanyInfo1> GetFlowCorpInfos(int pageIndex, int pageSize, string condition, out int counts, string areaCode)
        {
            ////调用DAL中的方法
            var list = new EnterpriseDAL().GetFlowCorpInfos(pageIndex, pageSize, condition, out counts);
            var dtolist = new List<Tb_Corp_CompanyInfo1>();
            foreach (var item in list)
            {
                Tb_Corp_CompanyInfo1 corpInfo_D = new Tb_Corp_CompanyInfo1();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(item, corpInfo_D);
                dtolist.Add(corpInfo_D);
            }
            return dtolist;
        }

        public override List<DTO.Tb_Corp_CompanyInfo> GetFlowCorpInfosSystem2(int pageIndex, int pageSize, string condition, out int counts, string areaCode)
        {
            ////调用DAL中的方法
            var list = new EnterpriseDAL().GetFlowCorpInfosSystem2(pageIndex, pageSize, condition, out counts);
            var dtolist = new List<DTO.Tb_Corp_CompanyInfo>();
            foreach (var item in list)
            {
                DTO.Tb_Corp_CompanyInfo corpInfo_D = new DTO.Tb_Corp_CompanyInfo();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(item, corpInfo_D);
                dtolist.Add(corpInfo_D);
            }
            return dtolist;
        }

        /// <summary>
        /// 修改外地入青信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="wdrq"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpInfoWDRQEdit(string corpUserGuid, DTO.tb_Corp_CompanyInfo_wdrq wdrq, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "corpUserGuid不正确！";
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    if (wdrq != null)
                    {
                        ////添加外地入青信息
                        var wdcorp = dbContext.Corp_CompanyInfosWdrq.Where(p => p.CorpUserGuid == cGuid).FirstOrDefault();
                        Entity.QD.tb_Corp_CompanyInfo_wdrq wdcorp_E = new Entity.QD.tb_Corp_CompanyInfo_wdrq();
                        ////用入参DTO为Entity赋值tb_Corp_CompanyInfo_wdrq
                        EntityHelper.ConvertEntity2OtherEntity(wdrq, wdcorp_E);
                        if (wdcorp != null)
                        {
                            ////修改赋值
                            EntityHelper.ConvertEntity2Entity<Entity.QD.tb_Corp_CompanyInfo_wdrq>(wdcorp_E, wdcorp);
                            dbContext.SaveChanges();
                            tran.Commit();
                            result.Message = "修改成功！";
                            result.Result = true;
                            result.ReturnValue = null;

                        }
                        else
                        {
                            result.Message = "修改失败，无该企业！";
                            result.Result = false;
                            result.ReturnValue = null;
                        }
                    }

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "修改失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }

            return result;
        }
        #endregion

        #region 验证企业是否存清出市场 作者：
        /// <summary>
        /// 验证企业是否存清出市场
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override string CheckCorp(string dogId, string areaCode)
        {
            ////1、企业信息 检查:未删除、审核通过、bCanBid包含4，如果是外地入青企业，检查外地入青证（Tb_Corp_CompanyInfo_wdrq）的有效期是否过期
            ////2、考核结果 检查对应资质的分数是否低于<60分
            string result = string.Empty;
            if (string.IsNullOrEmpty(dogId))
            {
                result = "1,企业狗号不能为空！";
                return JsonConvert.SerializeObject(result);
            }
            else
            {
                try
                {
                    int dogCode;
                    int.TryParse(dogId, out dogCode);
                    // Orderby 为报名时不取出代理企业
                    Entity.T_Sys_Users users = dbContext.T_Sys_Users.Where(m => m.DogID == dogCode).OrderBy(m => m.RoleID).FirstOrDefault();

                    if (users == null)
                    {
                        result = "1,该企业不存在或尚未通过审核，请检查接入数字设备是否正确！(1)";
                    }
                    else
                    {
                        ////1、企业信息 检查:未删除、审核通过、bCanBid包含4
                        Entity.QD.Tb_Corp_CompanyInfo corp = dbContext.Corp_CompanyInfos.Where(m => m.CorpUserGuid == users.UserGuid && (m.IsDel != true || m.IsDel == null) && m.FlowCode.StartsWith("1")).FirstOrDefault();
                        if (corp == null)
                        {
                            result = "1,该企业不存在或尚未通过审核，请检查接入数字设备是否正确！(2)";
                        }
                        else if (!string.IsNullOrEmpty(corp.bCanBid) && corp.bCanBid.IndexOf("4") < 0)
                        {
                            if (corp.tb_Corp_IsOuter == 1)  //如果是外地入青企业，检查外地入青证（Tb_Corp_CompanyInfo_wdrq）的有效期是否过期
                            {
                                Entity.QD.tb_Corp_CompanyInfo_wdrq corpwdrq = dbContext.Corp_CompanyInfosWdrq.Where(m => m.CorpGuid == corp.CorpGuid && m.FlowCode.StartsWith("1")).FirstOrDefault();
                                if (corpwdrq != null)
                                {
                                    if (!string.IsNullOrEmpty(corpwdrq.validDate))////有效期为空为null先不做处理
                                    {
                                        DateTime today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
                                        DateTime validdate = DateTime.Parse(corpwdrq.validDate);
                                        if (today >= validdate)////取当前日期与有效日期的相差天数判断是否在某一规定范围内比较合理
                                        {
                                            result = "1,外地入青证过期！";
                                            return JsonConvert.SerializeObject(result);
                                        }
                                    }
                                }
                                else
                                {
                                    result = "1,无外地入青证！";
                                    return JsonConvert.SerializeObject(result);
                                }
                            }

                            ////通过DogID、KindID取分数
                            ////验证去掉bGrade校验，外地入青企业bGrade=17，e_SorcePublish_2006表中为15，查不到记录 2013-10-29 毛凯
                            decimal? score = 0;
                            ////报名考核分取去年的 2014-5-14 小柴提出，王林恺确认
                            Entity.QD.e_SorcePublish_2006backup corpscore = dbContext.LastYearSorcePublish.Where(m => m.TreeID == users.DogID && m.bMain == true).FirstOrDefault();
                            if (corpscore != null)
                            {
                                if (corpscore.Year_Sorce != null)
                                {
                                    score = corpscore.Year_Sorce;
                                }
                            }
                            if (score < 60)  //2、考核结果 检查对应资质的分数是否低于60分 (是否为D级 ， 是D级 = 已清出市场)
                            {
                                result = "1,该企业由于考核分不足60分，已清出市场！";
                            }
                            else
                            {
                                result = "0,合格。";
                            }
                        }
                        else
                        {
                            result = "1,该企业已清出市场！";
                        }
                    }
                }
                catch (Exception ex)
                {
                    result = "1," + ex.Message + ex.StackTrace;
                }
            }
            return JsonConvert.SerializeObject(result);
        }
        #endregion

        #region 验证企业是否存清出市场 作者：毛凯
        /// <summary>
        /// 根据企业guid验证企业是否存清出市场
        /// 报名可能同一个dogid对应多个类型单位（施工、监理...），在选定某家单位后对该单位进行验证
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override string CheckCorpByCorpGuid(string corpGuid, string areaCode)
        {
            ////1、企业信息 检查:未删除、审核通过、bCanBid包含4，如果是外地入青企业，检查外地入青证（Tb_Corp_CompanyInfo_wdrq）的有效期是否过期
            ////2、考核结果 检查对应资质的分数是否低于<60分
            string result = string.Empty;
            Guid cid;
            if (string.IsNullOrEmpty(corpGuid))
            {
                result = "1,企业Guid不能为空！";
                return JsonConvert.SerializeObject(result);
            }
            else if (!Guid.TryParse(corpGuid, out cid))
            {
                result = "1,企业Guid格式不正确！";
                return JsonConvert.SerializeObject(result);
            }
            else
            {
                try
                {
                    ////1、企业信息 检查:未删除、审核通过、bCanBid包含4
                    Entity.QD.Tb_Corp_CompanyInfo corp = dbContext.Corp_CompanyInfos.Where(m => m.CorpGuid == cid && (m.IsDel != true || m.IsDel == null) && m.FlowCode.StartsWith("1")).FirstOrDefault();
                    Entity.T_Sys_Users users = corp == null ? null : dbContext.T_Sys_Users.Where(m => m.UserGuid == corp.CorpUserGuid).FirstOrDefault();
                    if (corp == null || users == null)
                    {
                        result = "1,该企业不存在或尚未通过审核，请检查接入数字设备是否正确！";
                    }
                    else if (!string.IsNullOrEmpty(corp.bCanBid) && corp.bCanBid.IndexOf("4") < 0)
                    {
                        //外地入青监理没有入青证，不进行检查，需求下次请弄清楚 
                        //现在只对classid=2501和2506进行外地入青证验证  2014-3-14 毛凯补充
                        if (corp.tb_Corp_IsOuter == 1&&(corp.classID==2501||corp.classID==2506))  //如果是外地入青企业，检查外地入青证（Tb_Corp_CompanyInfo_wdrq）的有效期是否过期
                        {
                            Entity.QD.tb_Corp_CompanyInfo_wdrq corpwdrq = dbContext.Corp_CompanyInfosWdrq.Where(m => m.CorpGuid == corp.CorpGuid && m.FlowCode.StartsWith("1")).FirstOrDefault();
                            if (corpwdrq != null)
                            {
                                if (!string.IsNullOrEmpty(corpwdrq.validDate))////有效期为空为null先不做处理
                                {
                                    DateTime today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
                                    DateTime validdate = DateTime.Parse(corpwdrq.validDate);
                                    if (today >= validdate)////取当前日期与有效日期的相差天数判断是否在某一规定范围内比较合理
                                    {
                                        result = "1,外地入青证过期！";
                                        return JsonConvert.SerializeObject(result);
                                    }
                                }
                            }
                            else
                            {
                                result = "1,无外地入青证！";
                                return JsonConvert.SerializeObject(result);
                            }
                        }

                        ////通过DogID、KindID取分数
                        ////验证去掉bGrade校验，外地入青企业bGrade=17，e_SorcePublish_2006表中为15，查不到记录 2013-10-29 毛凯
                        decimal? score = 0;
                        ////报名考核分取去年的 2014-5-14 小柴提出，王林恺确认
                        Entity.QD.e_SorcePublish_2006backup corpscore = dbContext.LastYearSorcePublish.Where(m => m.TreeID == users.DogID && m.bMain == true).FirstOrDefault();
                        if (corpscore != null)
                        {
                            if (corpscore.Year_Sorce != null)
                            {
                                score = corpscore.Year_Sorce;
                            }
                        }
                        if (score < 60)  //2、考核结果 检查对应资质的分数是否低于60分 (是否为D级 ， 是D级 = 已清出市场)
                        {
                            result = "1,该企业由于考核分不足60分，已清出市场！";
                        }
                        else
                        {
                            result = "0,合格。";
                        }
                    }
                    else
                    {
                        result = "1,该企业已清出市场！";
                    }
                }
                catch (Exception ex)
                {
                    result = "1," + ex.Message + ex.StackTrace;
                }
            }
            return JsonConvert.SerializeObject(result);
        }
        #endregion

        #region 企业解锁、加锁 作者：
        /// <summary>
        /// 加锁
        /// </summary>
        /// <param name="id"></param>
        public override bool LockCorpBCanBid(string corpGuid, string areaCode)
        {
            bool returnValue = false;
            Guid eGuid = Guid.Empty;
            if (Guid.TryParse(corpGuid, out eGuid))
            {
                Entity.QD.Tb_Corp_CompanyInfo currentCorp = dbContext.Corp_CompanyInfos.Where(p => p.CorpUserGuid == eGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                if (currentCorp != null)
                {
                    try
                    {
                        ////修改加锁状态
                        ////bCanBid 不含有1时，不可以招标 
                        if (!string.IsNullOrEmpty(currentCorp.bCanBid))
                        {
                            if (currentCorp.bCanBid.Contains(",1"))
                            {
                                currentCorp.bCanBid = currentCorp.bCanBid.Replace(",1", "");
                            }
                            else
                                if (currentCorp.bCanBid.Contains("1,"))
                                {
                                    currentCorp.bCanBid = currentCorp.bCanBid.Replace("1,", "");
                                }
                                else
                                    if (currentCorp.bCanBid.Contains("1"))
                                    {
                                        currentCorp.bCanBid = currentCorp.bCanBid.Replace("1", "");
                                    }
                            dbContext.SaveChanges();
                            ////记录日志
                            InsertUserLog("修改企业加锁状态", corpGuid, "8010", "2");
                        }
                        returnValue = true;
                    }
                    catch (Exception ex)
                    {
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });

                    }
                }
            }
            return returnValue;
        }

        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="id"></param>
        public override bool UnLockCorpBCanBid(string corpGuid, string areaCode)
        {
            bool returnValue = false;
            Guid eGuid = Guid.Empty;
            if (Guid.TryParse(corpGuid, out eGuid))
            {
                Entity.QD.Tb_Corp_CompanyInfo currentCorp = dbContext.Corp_CompanyInfos.Where(p => p.CorpUserGuid == eGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                if (currentCorp != null)
                {
                    try
                    {
                        ////修改人员加锁状态
                        ////bCanBid 含有1时，可以招标 
                        if (string.IsNullOrEmpty(currentCorp.bCanBid))
                        {
                            currentCorp.bCanBid = "1";
                        }
                        else
                        {
                            if (!currentCorp.bCanBid.Contains("1"))
                            {
                                currentCorp.bCanBid += ",1";
                            }
                        }

                        dbContext.SaveChanges();
                        ////记录日志
                        InsertUserLog("修改企业加锁状态", corpGuid, "8010", "2");
                        returnValue = true;
                    }
                    catch (Exception ex)
                    {
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });

                    }
                }
            }
            return returnValue;
        }
        #endregion

        #region 企业产量、产值、税金相关

        /// <summary>
        /// 根据年份查询企业是否有产量、产值、税金信息
        /// </summary>
        /// <param name="userGUID">企业GUID</param>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public override bool ExistsProfix(string userGUID, int year, int month, string areaCode)
        {
            bool result = false;

            var profitObj = dbContext.ProfitTotal.Where(p => p.CorpUserGuid == userGUID
                            && p.iYear == year && p.iMonth == month && p.IsDel != true).FirstOrDefault();
            if (profitObj != null)
            {
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 企业端获取企业产值、税金信息
        /// </summary>
        /// <param name="userGUID">企业GUID</param>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <param name="flowCode">审核状态</param>
        /// <returns></returns>
        public override List<DTO.Tb_Corp_ProfitTotal> GetListByYearUserGUID(string userGUID, int year, int month, string flowCode, string areaCode)
        {

            List<DTO.Tb_Corp_ProfitTotal> resultList = new List<DTO.Tb_Corp_ProfitTotal>();
            //获取招标代理企业
            var profitObj = from p in EnterDAL.GetProfitList(userGUID, year, month, flowCode, "")
                            select new DTO.Tb_Corp_ProfitTotal
                            {
                                ID = p.ID,
                                DogId = p.DogId,
                                CorpUserGuid = p.CorpUserGuid,
                                CorpName = p.CorpName,
                                iYear = p.iYear,
                                iMonth = p.iMonth,
                                ProjectCount = p.ProjectCount,
                                Turnover = p.Turnover,
                                ZBMoney = p.ZBMoney,
                                ContractMoney = p.ContractMoney,
                                TurnoverTax = p.TurnoverTax,
                                IncomeTax = p.IncomeTax,
                                OtherTax = p.OtherTax,
                                TaxTotal = p.TaxTotal,
                                CreateMan = p.CreateMan,
                                ContactTel = p.ContactTel,
                                Memo = p.Memo,
                                CreateTime = p.CreateTime,
                                IsDel = p.IsDel,
                                FlowCode = p.FlowCode,
                                ContractTotalMoney = p.ContractTotalMoney,
                                OtherContractMoney = p.OtherContractMoney,
                                TotalIncomeTax = p.TotalIncomeTax,
                                OtherIncomeTax = p.OtherIncomeTax,
                                WorkProfit = p.WorkProfit
                            };
            if (!string.IsNullOrEmpty(userGUID))
            {
                profitObj = profitObj.Where(p => p.CorpUserGuid == userGUID);
            }
            if (year != 0)
            {
                profitObj = profitObj.Where(p => p.iYear == year);
            }
            if (month != 0)
            {
                profitObj = profitObj.Where(p => p.iMonth == month);
            }
            if (!string.IsNullOrEmpty(flowCode))
            {
                profitObj = profitObj.Where(p => p.FlowCode == flowCode);
            }
            return profitObj.ToList();
        }

        /// <summary>
        /// 添加企业产值、税金信息
        /// </summary>
        /// <param name="DTOProfit">序列化DTO实体</param>
        /// <returns></returns>
        public override DTO.OperationResult AddProfit(DTO.Tb_Corp_ProfitTotal Profit, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    //1、添加Tb_Corp_ProfitTotal表数据
                    Entity.QD.Tb_Corp_ProfitTotal profit_E = new Entity.QD.Tb_Corp_ProfitTotal();
                    EntityHelper.ConvertEntity2OtherEntity(Profit, profit_E);
                    dbContext.ProfitTotal.Add(profit_E);
                    dbContext.SaveChanges();

                    //2、查询刚刚添加的数据的ID
                    Entity.QD.Tb_Corp_ProfitTotal profit_Add = dbContext.ProfitTotal.Where(p => p.IsDel != true && p.CorpUserGuid == Profit.CorpUserGuid && p.iYear == Profit.iYear && p.iMonth == Profit.iMonth).FirstOrDefault();
                    if (profit_Add != null)
                    {
                        //3、添加审批表tb_flowcode数据
                        Entity.QD.Tb_FlowCode flow = new Entity.QD.Tb_FlowCode();
                        flow.ObjectId = profit_Add.ID.ToString();
                        flow.AreaCode = "02";
                        flow.RoleId = "";
                        flow.UserId = "";
                        flow.Description = "";
                        flow.CodeType = 9060;//codeType为9060
                        flow.FlowCode = "0";
                        flow.UpdateTime = DateTime.Now;
                        flow.IsDel = false;
                        dbContext.FlowCodes.Add(flow);

                        dbContext.SaveChanges();
                        tran.Commit();
                        result.Result = true;
                        result.Message = "添加成功！";
                        result.ReturnValue = "";
                    }
                    else
                    {

                        result.Result = false;
                        result.Message = "添加失败！";
                        result.ReturnValue = "";
                        tran.Rollback();
                    }

                }
                catch (Exception ex)
                {
                    result.Result = false;
                    result.Message = "添加失败！" + ex.Message;
                    result.ReturnValue = "";
                    tran.Rollback();
                }
            }
            return result;
        }

        /// <summary>
        /// 根据ID获取企业产值、税金信息
        /// </summary>
        /// <param name="profitID">产值、税金ID</param>
        /// <returns></returns>
        public override DTO.Tb_Corp_ProfitTotal GetProfitByID(int profitID, string areaCode)
        {
            Entity.QD.Tb_Corp_ProfitTotal_View proView = EnterDAL.GetProfitByID(profitID.ToString());
            DTO.Tb_Corp_ProfitTotal proDTO = new DTO.Tb_Corp_ProfitTotal();
            if (proView != null)
            {
                proDTO.ID = proView.ID;
                proDTO.DogId = proView.DogId;
                proDTO.CorpUserGuid = proView.CorpUserGuid;
                proDTO.CorpName = proView.CorpName;
                proDTO.iYear = proView.iYear;
                proDTO.iMonth = proView.iMonth;
                proDTO.ProjectCount = proView.ProjectCount;
                proDTO.Turnover = proView.Turnover;
                proDTO.ZBMoney = proView.ZBMoney;
                proDTO.ContractMoney = proView.ContractMoney;
                proDTO.TurnoverTax = proView.TurnoverTax;
                proDTO.IncomeTax = proView.IncomeTax;
                proDTO.OtherTax = proView.OtherTax;
                proDTO.TaxTotal = proView.TaxTotal;
                proDTO.CreateMan = proView.CreateMan;
                proDTO.ContactTel = proView.ContactTel;
                proDTO.Memo = proView.Memo;
                proDTO.CreateTime = proView.CreateTime;
                proDTO.IsDel = proView.IsDel;
                proDTO.FlowCode = proView.FlowCode;
                proDTO.Description = proView.Description == null ? "" : proView.Description;
                proDTO.ContractTotalMoney = proView.ContractTotalMoney;
                proDTO.OtherContractMoney = proView.OtherContractMoney;
                proDTO.TotalIncomeTax = proView.TotalIncomeTax;
                proDTO.OtherIncomeTax = proView.OtherIncomeTax;
                proDTO.WorkProfit = proView.WorkProfit;
            }

            return proDTO;
        }

        /// <summary>
        /// 根据ID(多个)删除企业产值、税金信息
        /// </summary>
        /// <param name="profitID">产值、税金ID</param>
        /// <returns>>返回序列化OperationResult结果</returns>
        public override DTO.OperationResult DeleteProfitByIDS(string profitID, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                List<int> intProfitID = new List<string>(profitID.Split(',')).ConvertAll(i => Convert.ToInt32(i));
                //1、判断传入的ID，只有退回(0,019,021)的和未上报(0)的才可以删除
                var checkprofit = from p in EnterDAL.GetProfitList("", 0, 0, "", "")
                                  where p.FlowCode != "未上报" && p.FlowCode != "退回"
                                  && intProfitID.Contains(p.ID)
                                  select p;
                if (checkprofit.ToList().Count > 0)
                {
                    //如果选择的还有其他情况，则不能删除
                    result.Result = false;
                    result.Message = "只有未上报和退回的数据才可以删除，请确认后再执行删除操作！";
                    result.ReturnValue = "failed";
                }
                else
                {
                    //2、执行删除操作（更新IsDel字段为true）
                    var profitList = from p in dbContext.ProfitTotal
                                     where intProfitID.Contains(p.ID) && p.IsDel != true
                                     select p;
                    foreach (var item in profitList)
                    {
                        item.IsDel = true;
                    }
                    dbContext.SaveChanges();

                    result.Result = true;
                    result.Message = "删除成功！";
                    result.ReturnValue = "";
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = "删除失败！" + ex.Message;
                result.ReturnValue = "sysError";
            }
            return result;
        }

        /// <summary>
        /// 修改企业产值、税金信息
        /// </summary>
        /// <param name="DTOprofit">序列化DTO实体</param>
        /// <returns>>返回序列化OperationResult结果</returns>
        public override DTO.OperationResult UpdateProfitByID(DTO.Tb_Corp_ProfitTotal DTOprofit, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                //只有未上报和退回的单据可以修改
                if (DTOprofit.FlowCode == "0" || DTOprofit.FlowCode == "0,019,021")
                {
                    //1、查询数据库中税金表
                    Entity.QD.Tb_Corp_ProfitTotal profit_DB = dbContext.ProfitTotal.Where(p => p.ID == DTOprofit.ID).SingleOrDefault();

                    if (profit_DB != null)
                    {
                        //2、获取用户提交的值
                        Entity.QD.Tb_Corp_ProfitTotal profit_E = SetProfitFromDTO(profit_DB, DTOprofit);

                        dbContext.SaveChanges();
                        result.Result = true;
                        result.Message = "修改成功！";
                        result.ReturnValue = "";
                    }
                }
                else
                {
                    result.Result = false;
                    result.Message = "修改失败！只有未上报和退回的数据才可以修改！";
                    result.ReturnValue = "failed";
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = "修改失败！" + ex.Message;
                result.ReturnValue = "sysError";
            }

            return result;
        }

        /// <summary>
        /// 企业上报税金数据
        /// </summary>
        /// <param name="profitID">产值、税金ID</param>
        /// <returns>>返回序列化OperationResult结果</returns>
        public override DTO.OperationResult SBProfitByIDS(string profitID, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                List<int> intProfitID = new List<string>(profitID.Split(',')).ConvertAll(i => int.Parse(i));
                //1、判断传入的ID，只有退回(0,019,021)的和未上报(0)的才可以上报
                var checkprofit = from p in EnterDAL.GetProfitList("", 0, 0, "", "")
                                  where p.FlowCode != "未上报" && p.FlowCode != "退回"
                                  && intProfitID.Contains(p.ID)
                                  select p;
                if (checkprofit.ToList().Count > 0)
                {
                    //如果选择的还有其他情况，则不能上报
                    result.Result = false;
                    result.Message = "只有未上报和退回的数据才可以上报，请确认后再执行上报操作！";
                    result.ReturnValue = "failed";
                }
                else
                {
                    //2、执行上报操作（更新flowcode字段为）

                    List<string> StrProfitID = new List<string>(profitID.Split(','));

                    var profitList = from f in dbContext.FlowCodes
                                     where StrProfitID.Contains(f.ObjectId) && f.CodeType == 9060
                                     select f;
                    foreach (var item in profitList)
                    {
                        if (item.FlowCode == "0")
                        {
                            //未上报的更新为已上报未审核
                            item.FlowCode = "0,019";
                        }
                        else if (item.FlowCode == "0,019,021")
                        {
                            //退回的更新为再次上报
                            item.FlowCode = "0,019,022";
                        }
                        item.UpdateTime = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                    }
                    dbContext.SaveChanges();

                    result.Result = true;
                    result.Message = "上报成功！";
                    result.ReturnValue = "";
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = "上报失败！" + ex.Message;
                result.ReturnValue = "sysError";
            }
            return result;
        }

        /// <summary>
        /// 主管审核企业产值、税金信息
        /// </summary>
        /// <param name="profitID">产值、税金ID</param>
        /// <param name="type">1：审核，2：退回</param>
        /// <param name="checkMemo">审核意见</param>
        /// <returns>>返回序列化OperationResult结果</returns>
        public override DTO.OperationResult CheckProfitByIDS(string profitID, int type, string checkMemo, bool isunlockandback, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string checkAction = "";
            try
            {
                switch (type)
                {
                    case 1:
                        checkAction = "审核";
                        break;
                    case 2:
                        checkAction = "退回";
                        break;
                    default:
                        break;
                }
                List<int> intProfitID = new List<string>(profitID.Split(',')).ConvertAll(i => int.Parse(i));
                //1、判断传入的ID，只有已上报或者再次上报才可以审核
                var checkprofit = from p in EnterDAL.GetProfitList("", 0, 0, "", "")
                                  where p.FlowCode != "已上报" && p.FlowCode != "再次上报"
                                  && intProfitID.Contains(p.ID)
                                  select p;
                if (checkprofit.ToList().Count > 0 && !isunlockandback)
                {
                    //如果选择的还有其他情况，则不能上报
                    result.Result = false;
                    result.Message = "只有已上报或者再次上报的数据才可以" + checkAction + "，请确认后再执行" + checkAction + "操作！";
                    result.ReturnValue = "failed";
                }
                else
                {
                    //2、执行审核操作（更新flowcode字段）

                    List<string> StrProfitID = new List<string>(profitID.Split(','));

                    var profitList = from f in dbContext.FlowCodes
                                     where StrProfitID.Contains(f.ObjectId) && f.CodeType == 9060
                                     select f;
                    foreach (var item in profitList)
                    {
                        if (type == 1)
                        {
                            //审核操作
                            item.FlowCode = "1,019,029";
                        }
                        else if (type == 2)
                        {
                            //退回
                            item.FlowCode = "0,019,021";
                        }
                        item.Description = checkMemo;
                    }
                    dbContext.SaveChanges();

                    result.Result = true;
                    result.Message = checkAction + "成功！";
                    result.ReturnValue = "";
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = checkAction + "失败！" + ex.Message;
                result.ReturnValue = "sysError";
            }
            return result;
        }

        /// <summary>
        /// 主管端获取企业产值、税金信息
        /// </summary>
        /// <param name="corpName">企业名称</param>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <param name="flowCode">审核状态</param>
        /// <returns></returns>
        public override List<DTO.Tb_Corp_ProfitTotal> GetProfitListForManager(string corpUserGuid, string corpName, int year, int month, string flowCode, string areaCode)
        {
            List<DTO.Tb_Corp_ProfitTotal> resultList = new List<DTO.Tb_Corp_ProfitTotal>();
            //获取招标代理企业
            var profitObj = from p in EnterDAL.GetProfitList(corpUserGuid, year, month, flowCode, corpName)
                            where p.FlowCode != "未上报"
                            select new DTO.Tb_Corp_ProfitTotal
                            {
                                ID = p.ID,
                                DogId = p.DogId,
                                CorpUserGuid = p.CorpUserGuid,
                                CorpName = p.CorpName,
                                iYear = p.iYear,
                                iMonth = p.iMonth,
                                ProjectCount = p.ProjectCount,
                                Turnover = p.Turnover,
                                ZBMoney = p.ZBMoney,
                                ContractMoney = p.ContractMoney,
                                TurnoverTax = p.TurnoverTax,
                                IncomeTax = p.IncomeTax,
                                OtherTax = p.OtherTax,
                                TaxTotal = p.TaxTotal,
                                CreateMan = p.CreateMan,
                                ContactTel = p.ContactTel,
                                Memo = p.Memo,
                                CreateTime = p.CreateTime,
                                IsDel = p.IsDel,
                                FlowCode = p.FlowCode,
                                ContractTotalMoney = p.ContractTotalMoney,
                                OtherIncomeTax = p.OtherIncomeTax,
                                OtherContractMoney = p.OtherContractMoney,
                                TotalIncomeTax = p.TotalIncomeTax,
                                WorkProfit = p.WorkProfit
                            };
            if (year != 0)
            {
                profitObj = profitObj.Where(p => p.iYear == year);
            }
            if (month != 0)
            {
                profitObj = profitObj.Where(p => p.iMonth == month);
            }
            if (!string.IsNullOrEmpty(flowCode))
            {
                profitObj = profitObj.Where(p => p.FlowCode == flowCode);
            }
            if (!string.IsNullOrEmpty(corpName))
            {
                profitObj = profitObj.Where(p => p.CorpName.Contains(corpName));
            }
            if (!string.IsNullOrEmpty(corpUserGuid))
            {
                profitObj = profitObj.Where(p => p.CorpUserGuid == corpUserGuid);
            }
            return profitObj.ToList();
        }


        public override List<RN.ERP.Entity.QD.tb_Corp_ProfitTotal_GetMonthProfitTotalStat> GetProfitGuidListForManager(string corpName, int year, string areaCode)
        {
            #region 源代码
            //Tb_Corp_ProfitTotalSum nullSum = new Tb_Corp_ProfitTotalSum();
            ////获取招标代理企业
            //var profitObj = from pguid in EnterDAL.GetProfitGuidList()
            //                join corp in dbContext.Corp_CompanyInfos on pguid.CorpUserGuid equals corp.CorpUserGuid.ToString()
            //                into leftcorp
            //                from lcorp in leftcorp.DefaultIfEmpty()

            //                join sumprofit in EnterDAL.GetSumProfitMoney() on pguid.CorpUserGuid equals sumprofit.CorpUserguid
            //                into leftsum
            //                from lsum in leftsum.DefaultIfEmpty()


            //                join flow in dbContext.FlowCodes on pguid.flowid equals flow.Id
            //                into leftflow
            //                from lflow in leftflow.DefaultIfEmpty()

            //                select new DTO.Tb_Corp_ProfitTotal
            //                {
            //                    CorpUserGuid = pguid.CorpUserGuid,
            //                    CorpName = lcorp.CorpName,
            //                    iYear = pguid.iYear,
            //                    iMonth = pguid.iMonth,
            //                    FlowCode = lflow.FlowCode,
            //                    updatetime = lflow.UpdateTime,
            //                    SUMProjectCount = (lsum ?? nullSum).SUMProjectCount,
            //                    SUMZBMoney = (lsum ?? nullSum).SUMZBMoney,
            //                    SUMContractTotalMoney = (lsum ?? nullSum).SUMContractTotalMoney,
            //                    SUMContractMoney = (lsum ?? nullSum).SUMContractMoney,
            //                    SUMOtherContractMoney = (lsum ?? nullSum).SUMOtherContractMoney,
            //                    SUMTotalIncomeTax = (lsum ?? nullSum).SUMTotalIncomeTax,
            //                    SUMTurnover = (lsum ?? nullSum).SUMTurnover,
            //                    SUMOtherIncomeTax = (lsum ?? nullSum).SUMOtherIncomeTax,
            //                    SUMWorkProfit = (lsum ?? nullSum).SUMWorkProfit,
            //                    SUMTaxTotal = (lsum ?? nullSum).SUMTaxTotal
            //                };


            //if (!string.IsNullOrEmpty(corpName))
            //{
            //    profitObj = profitObj.Where(p => p.CorpName.Contains(corpName));
            //}
            //if (year != 0)
            //{
            //    profitObj = profitObj.Where(p => p.iYear == year);
            //}
            //profitObj = profitObj.Where(p => p.FlowCode != "0").OrderBy(p => p.FlowCode);

            //return profitObj.ToList();
            #endregion

            return EnterDAL.GetProfitGuidListForManager(corpName, year, areaCode);
        }



        /// <summary>
        /// 用DTO的税金值给Entity的税金值赋值
        /// </summary>
        /// <param name="profit_D"></param>
        private Entity.QD.Tb_Corp_ProfitTotal SetProfitFromDTO(Entity.QD.Tb_Corp_ProfitTotal profit_E, DTO.Tb_Corp_ProfitTotal profit_D)
        {
            profit_E.ProjectCount = profit_D.ProjectCount;
            profit_E.Turnover = profit_D.Turnover;
            profit_E.ZBMoney = profit_D.ZBMoney;
            profit_E.ContractMoney = profit_D.ContractMoney;
            profit_E.TurnoverTax = profit_D.TurnoverTax;
            profit_E.IncomeTax = profit_D.IncomeTax;
            profit_E.OtherTax = profit_D.OtherTax;
            profit_E.TaxTotal = profit_D.TaxTotal;
            profit_E.CreateMan = profit_D.CreateMan;
            profit_E.ContactTel = profit_D.ContactTel;
            profit_E.Memo = profit_D.Memo;

            profit_E.ContractTotalMoney = profit_D.ContractTotalMoney;
            profit_E.OtherContractMoney = profit_D.OtherContractMoney;
            profit_E.TotalIncomeTax = profit_D.TotalIncomeTax;
            profit_E.OtherIncomeTax = profit_D.OtherIncomeTax;
            profit_E.WorkProfit = profit_D.WorkProfit;

            return profit_E;
        }

        /// <summary>
        /// 获得审批状态
        /// </summary>
        /// <param name="flowCode">审批串</param>
        /// <returns></returns>
        private string GetFlowCodeTitle(string flowCode)
        {
            string result = "";
            switch (flowCode)
            {
                case "0":
                    result = "未上报";
                    break;
                case "0,019":
                    result = "未审核";
                    break;
                case "0,019,021":
                    result = "退回";
                    break;
                case "1,019,029":
                    result = "已审核";
                    break;
                case "0,019,022":
                    result = "再次上报";
                    break;
                default:
                    result = "未上报";
                    break;
            }
            return result;
        }

        /// <summary>
        /// 同时添加一个企业某一年的产量，产值，税金记录
        /// </summary>
        /// <param name="year">年</param>
        /// <param name="userGUID">userGUID</param>
        /// <param name="dogID">dogID</param>
        /// <param name="corpName">企业名称</param>
        /// <returns></returns>
        public override bool AddList(string year, string userGUID, string dogID, string corpName, string areaCode)
        {
            bool result = false;
            /*
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    //增加3个类型的数据
                    for (int i = 1; i <= 3; i++)
                    {
                        Entity.QD.Tb_Corp_ProfitTotal profix = new Entity.QD.Tb_Corp_ProfitTotal();
                        profix.UserGuid = userGUID;
                        profix.years = Convert.ToInt32(year);
                        profix.unitid = dogID;
                        profix.dogid = dogID;
                        profix.firstyield = 0;
                        profix.secondyield = 0;
                        profix.thirdyield = 0;
                        profix.fourthyield = 0;
                        profix.fifthsyield = 0;
                        profix.sixthyield = 0;
                        profix.seventhyield = 0;
                        profix.eighthyield = 0;
                        profix.ninthyield = 0;
                        profix.tenthyidle = 0;
                        profix.eleventhyield = 0;
                        profix.twelfthyield = 0;
                        profix.unitname = corpName;
                        profix.infoType = i;
                        profix.FlowCode = "0";
                        dbContext.ProfitTotal.Add(profix);
                        dbContext.SaveChanges();
                    }

                    //添加审核表
                    Entity.QD.Tb_FlowCode flow = new Entity.QD.Tb_FlowCode();
                    flow.ObjectId = userGUID + "_" + year;
                    flow.AreaCode = "02";
                    flow.RoleId = "";
                    flow.UserId = "";
                    flow.Description = "";
                    flow.CodeType = 9060;//codeType为9060
                    flow.FlowCode = "0";
                    flow.UpdateTime = DateTime.Now;
                    flow.IsDel = false;
                    dbContext.FlowCodes.Add(flow);

                    dbContext.SaveChanges();
                    tran.Commit();
                    result = true;
                }
                catch (Exception ex)
                {
                    result = false;
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message + "；企业添加产量信息错误！",
                        LogDate = DateTime.Now
                    });
                }
            }
            */
            return result;
        }

        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public override bool UpdateInfoTotalList(List<DTO.Tb_Corp_ProfitTotal> list, string areaCode)
        {
            bool result = false;
            /*
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    if (list.Count > 0)
                    {

                        foreach (DTO.Tb_Corp_ProfitTotal item in list)
                        {
                            ////查询数据库
                            Entity.QD.Tb_Corp_ProfitTotal dbCorpInfo = dbContext.ProfitTotal.Where(p => p.ID == item.ID).FirstOrDefault();
                            if (dbCorpInfo != null)
                            {
                                //得到用户发送的实体类
                                Entity.QD.Tb_Corp_ProfitTotal p_E = new Entity.QD.Tb_Corp_ProfitTotal();
                                EntityHelper.ConvertEntity2OtherEntity(item, p_E);
                                EntityHelper.ConvertEntity2Entity(p_E, dbCorpInfo);
                                dbContext.SaveChanges();
                            }
                        }



                        string flowObjectID = list[0].UserGuid + "_" + list[0].years;
                        ////查询审批流数据
                        Entity.QD.Tb_FlowCode dbFlow = dbContext.FlowCodes.Where(f => f.ObjectId == flowObjectID).FirstOrDefault();
                        if (dbFlow != null)
                        {
                            dbFlow.FlowCode = "0,019";
                            dbContext.SaveChanges();
                        }
                        tran.Commit();

                        result = true;
                    }
                }
                catch (Exception ex)
                {
                    result = false;
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message + "；企业更改产量信息错误！",
                        LogDate = DateTime.Now
                    });
                    throw ex;
                }
            }
            */
            return result;
        }

        /// <summary>
        /// 主管查询企业的产量，产值，税金信息
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="corpName">企业名称</param>
        /// <param name="areaCode">地区</param>
        /// <param name="flowState">审核状态：已审核、未审核</param>
        /// <returns></returns>
        public override List<DTO.Tb_Corp_ProfitTotal> GetListForManager(string year, string corpName, string areaCode, string flowState)
        {
            StringBuilder sql = new StringBuilder("");
            List<DTO.Tb_Corp_ProfitTotal> resultList = new List<DTO.Tb_Corp_ProfitTotal>();
            /*
            sql.Append(" select p.*, ");
            sql.Append(" case when f.flowcode='0,019' then '已上报(未审核)'  ");
            sql.Append(" when f.flowcode='0' then '未上报' ");
            sql.Append(" when f.flowcode='0,019,021' then '退回' ");
            sql.Append(" when f.flowcode='1,019,029' then '已审核' ");
            sql.Append(" else '未审核' end as FlowCode ");
            sql.Append(" from tb_Corp_ProfitTotal p ");
            sql.Append(" inner join t_sys_users u on p.userguid=u.userguid and u.roleid in (105,99105) ");//只查询招标代理企业
            sql.Append(" left join tb_flowcode f on p.userguid+'_'+Convert(varchar,p.years) = f.objectid ");
            sql.Append(" where f.flowcode <> '0' ");//不查询未上报的数据
            if (year != "")
            {
                sql.Append(" and p.years = ").Append(year).Append(" ");
            }
            if (corpName != "")
            {
                sql.Append(" and p.unitname like '%").Append(corpName).Append("%' ");
            }
            if (flowState != "")
            {
                sql.Append(" and f.flowcode = '").Append(flowState).Append("' ");
            }
            sql.Append(" order by p.years desc,p.userguid,f.flowcode ");

            List<Entity.QD.Tb_Corp_ProfitTotal> list = dbContext.Database.SqlQuery<Entity.QD.Tb_Corp_ProfitTotal>(sql.ToString()).ToList();
            if (list.Count > 0)
            {
                foreach (Entity.QD.Tb_Corp_ProfitTotal item in list)
                {
                    DTO.Tb_Corp_ProfitTotal p_D = new DTO.Tb_Corp_ProfitTotal();
                    EntityHelper.ConvertEntity2OtherEntity(item, p_D);
                    resultList.Add(p_D);
                }
            }
            */
            return resultList;
        }

        /// <summary>
        /// 主管批量审核
        /// </summary>
        /// <param name="list">由userGUID+"_"+年份组成的键值对集合</param>
        /// <param name="ActionType">用户执行的操作：1代表审核，2代表退回，3代表弃审</param>
        /// <returns></returns>
        public override bool CheckProfit(List<string> list, int ActionType, string areaCode)
        {
            bool result = false;
            /*
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    string ActionStr = "0,019";
                    switch (ActionType)
                    {
                        case 1: //审核操作
                            ActionStr = "1,019,029";
                            break;
                        case 2: //退回操作
                            ActionStr = "0,019,021";
                            break;
                        case 3: //弃审操作
                            ActionStr = "0,019";
                            break;
                        default:
                            break;
                    }
                    foreach (string item in list)
                    {
                        ////查询数据库
                        Entity.QD.Tb_FlowCode dbFlow = dbContext.FlowCodes.Where(p => p.ObjectId == item).FirstOrDefault();
                        //得到用户发送的实体类
                        if (dbFlow != null)
                        {
                            dbFlow.FlowCode = ActionStr;
                            dbFlow.UpdateTime = DateTime.Now;
                            dbContext.SaveChanges();
                        }
                    }

                    tran.Commit();
                    result = true;
                }
                catch (Exception ex)
                {
                    result = false;
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message + "；主管审核产量信息错误！",
                        LogDate = DateTime.Now
                    });
                }
            }
            */
            return result;
        }

        #endregion

        #region 业绩申报：添加，修改，审核，上报

        /// <summary>
        /// 业绩资质
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override string GetQualityByOuterPrizeID(string id, string areaCode)
        {
            int eid = 0;
            if (int.TryParse(id, out eid))
            {
                var qualityGuidList = from e in dbContext.e_Outerprize
                                      where e.ID == eid
                                      select e.QualityGuid;
                var qualityList = from q in dbContext.Corp_CompanyQualities
                                  where qualityGuidList.Contains(q.QualityGuid)
                                  select q;
                if (qualityGuidList != null)
                {
                    return JsonConvert.SerializeObject(qualityGuidList.ToList());
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }

        public override string CodeZjjg_bind(string areaCode)
        {
            var list = from z in dbContext.a_zjjg
                       select new
                       {
                           z.code,
                           z.title
                       };
            return JsonConvert.SerializeObject(list.ToList());

        }
        public override string BindStructKind(string areaCode)
        {
            var list = from s in dbContext.a_StructKind
                       select s;
            return JsonConvert.SerializeObject(list.ToList());


        }

        #endregion

        #region 工程业绩列表(暂不使用，使用项目库的服务)

        /// <summary>
        /// 主管端获取工程业绩列表
        /// </summary>
        /// <param name="corpName">企业名称</param>
        /// <param name="projectName">工程名称</param>
        /// <param name="flowCode">审核状态</param>
        /// <returns></returns>
        public override List<DTO.e_OuterPrize> GetProjectYJListForManager(string corpName, string projectName, string flowCode, string areaCode)
        {
            return null;
        }

        /// <summary>
        /// 企业端获取工程业绩列表
        /// </summary>
        /// <param name="corpUserGUID">企业名称GUID</param>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <param name="flowCode">审核状态</param>
        /// <returns></returns>
        public override List<DTO.e_OuterPrize> GetProjectYJListForCorp(string corpUserGUID, string projectName, string flowCode, string areaCode)
        {
            int[] roleList = new int[] { 105, 99105 };
            List<DTO.e_OuterPrize> list = new List<DTO.e_OuterPrize>();
            var query = from e in dbContext.e_Outerprize
                        join u in dbContext.T_Sys_Users on e.CorpUserGuid equals u.UserGuid
                        where roleList.Contains(u.RoleID ?? 0)
                        select new DTO.e_OuterPrize
                        {
                            ID = e.ID,
                            CorpUserGuid = e.CorpUserGuid,
                            ProjectName = e.ProjectName,
                            ManagerName = e.ManagerName,
                            ManagerCode = e.ManagerCode,
                            ApplyCost = e.ApplyCost,
                            ApplyArea = e.ApplyArea,
                            AuditCost = e.AuditCost,
                            AuditArea = e.AuditArea,
                            EndDate = e.EndDate,
                            bFlowStatus = e.bFlowStatus
                        };
            if (!string.IsNullOrEmpty(corpUserGUID))
            {
                Guid userGUID = new Guid(corpUserGUID);
                query.Where(e => e.CorpUserGuid == userGUID);
            }
            if (!string.IsNullOrEmpty(projectName))
            {
                query.Where(e => e.ProjectName.Contains(projectName));
            }
            if (!string.IsNullOrEmpty(flowCode))
            {
                if (flowCode == "未上报")
                {
                    query.Where(e => e.bFlowStatus == "0");
                }
                else if (flowCode == "已上报")
                {

                }
                else if (flowCode == "退回")
                {
                    query.Where(e => e.bFlowStatus.Contains(",011,"));
                }
                else if (flowCode == "审核通过")
                {
                    query.Where(e => (e.bFlowStatus.Contains(",019,") && !e.bFlowStatus.Contains(",021,")) || e.bFlowStatus.Contains("1,"));
                }
            }
            list = query.ToList();
            return list;
        }

        /// <summary>
        /// 企业端删除工程
        /// </summary>
        /// <param name="ID">工程ID</param>
        /// <returns></returns>
        public override DTO.OperationResult DelProjectYJByIDS(string ID, string areaCode)
        {

            DTO.OperationResult result = new DTO.OperationResult();

            try
            {
                List<int> IDList = new List<string>(ID.Split(',')).ConvertAll(i => Convert.ToInt32(i));
                //判断选择的是否全部为未上报的数据，只有未上报的才可以删除
                var queryCheck = dbContext.e_Outerprize.Where(e => e.bFlowStatus != "0").ToList();
                if (queryCheck != null && queryCheck.Count > 0)
                {
                    result.Result = false;
                    result.ReturnValue = "failed";
                    result.Message = "只能删除未上报的数据，请确认后再执行删除操作！";
                }
                else
                {
                    //2、执行删除操作（更新IsDel字段为true）
                    var projectList = from e in dbContext.e_Outerprize
                                      where IDList.Contains(e.ID) && e.bFlowStatus != "0"
                                      select e;
                    foreach (var item in projectList)
                    {
                        dbContext.e_Outerprize.Remove(item);
                    }
                    dbContext.SaveChanges();

                    result.Result = true;
                    result.Message = "删除成功！";
                    result.ReturnValue = "";
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = "删除失败！" + ex.Message;
                result.ReturnValue = "sysError";
            }

            return result;
        }

        #endregion

        #region 根据省库KeyID获取青岛企业信息
        public override string GetCorpInfoForDL(string dogID, string areaCode)
        {
            var dbUsers = dbContext.T_Sys_Users;
            var dbCorpInfo = dbContext.Corp_CompanyInfos;

            int[] roleidlist = { 105, 99105 };
            int dogid = Convert.ToInt32(dogID);
            var query = from u in dbUsers
                        join c in dbCorpInfo on u.UserGuid equals c.CorpUserGuid into emptitledetails
                        from emptitle in emptitledetails.DefaultIfEmpty()
                        where u.KeyId == dogid
                        && roleidlist.Contains((int)u.RoleID)
                        select new CompanyInfoDL
                        {
                            DogID = u.DogID,
                            CorpID = u.CorpID,
                            UserGuid = u.UserGuid,
                            RoleID = u.RoleID,
                            CorpName = emptitle.CorpName
                        };
            if (query != null)
            {
                return JsonConvert.SerializeObject(query);
            }
            return string.Empty;
        }

        public override string GetCompanyinfoByZbdlDogid(int dogid)
        {
            var qdCorps = dbContext.Corp_CompanyInfos;
            var qdUsers = dbContext.T_Sys_Users;
            var query = from qdUser in qdUsers
                        join qdCorp in qdCorps on qdUser.UserGuid equals qdCorp.CorpUserGuid
                        where qdUser.KeyId == dogid
                        select new
                        {
                            DogId = qdUser.DogID,
                            CorpId = qdCorp.ID,
                            RoleId = qdUser.RoleID,
                            Title = qdCorp.CorpName,
                            Guid = qdUser.UserGuid
                        };
            return JsonConvert.SerializeObject(query.FirstOrDefault());
        }

        #endregion

        #region 青岛招标代理系统首页企业信息统计
        public override IList<CorpStatisModel> CorpStatis(string isNative, int roleid, int corpkindid, string areacode)
        {
            var corp = dbContext.Corp_CompanyInfos;
            var users = dbContext.T_Sys_Users;
            var corpquality = dbContext.Corp_CompanyQualities;

            var query = from tcc in corp
                        join T in users on new { CorpUserGuid = (Guid)tcc.CorpUserGuid } equals new { CorpUserGuid = T.UserGuid } into T_join
                        from T in T_join.DefaultIfEmpty()
                        join cq in corpquality on tcc.CorpUserGuid equals cq.CorpUserGuid into cq_join
                        from cq in cq_join.DefaultIfEmpty()
                        where
                          cq.KindID == corpkindid &&
                          cq.IsDel == false &&
                          tcc.FlowCode.StartsWith("1,") &&
                          T.DogID > 0 &&
                          (T.RoleID == 105 || T.RoleID == 99105)
                        group new { cq, tcc } by new
                        {
                            cq.GradeCode,
                            tcc.tb_Corp_IsOuter
                        } into g
                        orderby
                          g.Key.GradeCode
                        select new CorpStatisModel
                        {
                            Count = (Int32?)g.Count(),
                            GradeCode = g.Key.GradeCode,
                            tb_Corp_IsOuter = (Int32?)g.Key.tb_Corp_IsOuter
                        };

            if (!string.IsNullOrEmpty(isNative))
            {
                query = query.Where(q => q.tb_Corp_IsOuter == (isNative == "1" ? 1 : 0));
            }
            IList<CorpStatisModel> lists = query.ToList<CorpStatisModel>();
            return lists;
        }

        public override IList<CorpInfoModel> GetCorpList(string queryCondition, out int count, string areaCode)
        {
            var corp = dbContext.Corp_CompanyInfos;
            var users = dbContext.T_Sys_Users;
            var corpquality = dbContext.Corp_CompanyQualities;

            var query = from tcc in corp
                        join T in users on new { CorpUserGuid = (Guid)tcc.CorpUserGuid } equals new { CorpUserGuid = T.UserGuid } into T_join
                        from T in T_join.DefaultIfEmpty()
                        join cq in corpquality on tcc.CorpUserGuid equals cq.CorpUserGuid into cq_join
                        from cq in cq_join.DefaultIfEmpty()
                        where cq.KindID == 132 &&
                          cq.IsDel == false &&
                          tcc.FlowCode.StartsWith("1,") &&
                          T.DogID > 0 &&
                          (T.RoleID == 105 || T.RoleID == 99105)
                        orderby cq.GradeCode
                        select new CorpInfoModel
                        {
                            CorpUserGuid = (Guid)tcc.CorpUserGuid,
                            CorpName = tcc.CorpName,
                            Address = tcc.Address,
                            LinkMan1 = tcc.LinkMan1,
                            Tel = tcc.Tel,
                            classID = tcc.classID,
                            KindID = cq.KindID,
                            FlowCode = tcc.FlowCode,
                            GradeCode = cq.GradeCode,
                            tb_Corp_IsOuter = tcc.tb_Corp_IsOuter,
                            DetailName = cq.DetailName + "-" + cq.GradeName
                        };


            if (!string.IsNullOrEmpty(queryCondition))
            {
                CorpInfoModel queryconditon = JsonConvert.DeserializeObject<CorpInfoModel>(queryCondition);
                //if (queryconditon.classID != null)
                //{
                //    query = query.Where(q => q.classID == queryconditon.classID);
                //}
                //if (queryconditon.KindID != null)
                //{
                //    query = query.Where(q => q.KindID == queryconditon.KindID);
                //}
                if (!string.IsNullOrEmpty(queryconditon.CorpName))
                {
                    query = query.Where(q => q.CorpName.Contains(queryconditon.CorpName));
                }
                //if (!string.IsNullOrEmpty(queryconditon.FlowCode))
                //{
                //    query = query.Where(q => q.FlowCode.StartsWith(queryconditon.FlowCode));
                //}
                if (!string.IsNullOrEmpty(queryconditon.GradeCode))
                {
                    query = query.Where(q => q.GradeCode == queryconditon.GradeCode);
                }
                if (queryconditon.tb_Corp_IsOuter != null)
                {
                    query = query.Where(q => q.tb_Corp_IsOuter == queryconditon.tb_Corp_IsOuter);
                }
            }
            count = query.ToList<CorpInfoModel>().Count();
            return query.ToList<CorpInfoModel>();
        }

        public override IList<CompanyInfo> GetZBDLCompanyInfo(QueryCompanyInfoConditionZBDL condition, int pageSize, int pageNum, string areaCondition)
        {
            var dbCompanies = dbContext.Corp_CompanyInfos;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on company.CorpUserGuid equals qualities.CorpUserGuid
                        into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        where company.AreaCode == "02" && quality.IsMain == true && quality.IsDel == false
                        select new CompanyInfo
                        {
                            #region 封装实体

                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.FlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode
                            #endregion
                        };
            if (condition != null)
            {
                if (condition.classID != null)
                {
                    query = query.Where(q => q.classID == condition.classID);
                }
                if (!string.IsNullOrEmpty(condition.FlowCode))
                {
                    query = query.Where(q => q.FlowCode.StartsWith(condition.FlowCode));
                }
                if (condition.KindID != null)
                {
                    query = query.Where(q => q.KindID == condition.KindID);
                }

                if (!string.IsNullOrEmpty(condition.CorpName))
                {
                    query = query.Where(q => q.CorpName.Contains(condition.CorpName));
                }
                if (condition.IsNative == "1")
                {
                    if (!string.IsNullOrEmpty(condition.AreaCode))
                    {
                        query = query.Where(q => q.AreaCode.StartsWith("02"));
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(condition.AreaCode))
                    {
                        query = query.Where(q => !q.AreaCode.StartsWith("02"));
                    }
                }

            }
            var result = new List<DTO.CompanyInfo>();
            if (pageSize > 0)
            {
                result = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                result = query.ToList();
            }

            return result;
        }

        #endregion
    }


}
